package com.ws.shop.action.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ws.shop.bean.Page;
import com.ws.shop.entity.Category;
import com.ws.shop.service.CategoryService;
import com.ws.shop.util.RequestUtil;

@Controller
@RequestMapping(value="/admin/category/*")
public class CategoryAction extends BaseAdminAction{
	private static Logger log = Logger.getLogger(CategoryAction.class);
	@Autowired
	private CategoryService categoryService;

	@RequestMapping(value="index.jhtml",method=RequestMethod.GET)
	public String index(HttpServletRequest request,Model model){
		int pageno = RequestUtil.getIntParameter(request, Page.PAGE_NO, 1);
		String q_categoryname = RequestUtil.getStringParameterByGet(request, "q_categoryname", null);
		try{
			Page page = categoryService.findCategoryListByPage(pageno,0,q_categoryname);
			model.addAttribute(Page.PAGE, page);
			model.addAttribute("q_categoryname",q_categoryname);
			return "category_index";
		}catch(Exception e){
			log.error("查询商品分类失败",e);
			return ERROR;
		}
	}
	
	@RequestMapping(value="input.jhtml",method=RequestMethod.GET)
	public String input(HttpServletRequest request,Model model){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		if(id > 0){
			Category category = categoryService.getCategory(id);
			model.addAttribute("category", category);
		}
		return "category_input";
	}
	
	@RequestMapping(value="save.jhtml",method=RequestMethod.POST)
	public String save(HttpServletRequest request,HttpServletResponse response){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		String categoryname = RequestUtil.getStringParameter(request, "categoryname", null);
		if(categoryname == null)
			return this.ajaxJsonErrorMessage(response, "商品分类名称不能为空");
		Category category = new Category(id,categoryname,0);
		try{
			categoryService.saveOrUpdate(category);
			return this.ajaxJsonSuccessMessage(response, "操作成功");
		}catch(Exception e){
			log.error("操作失败："+category,e);
			return this.ajaxJsonErrorMessage(response, "系统繁忙，请稍后再试");
		}
	}
}
